#import "ALAppInfoPopoverController.h"
#import "ALApp.h"
#import "ALVersion.h"


#pragma mark Constants


#pragma mark -
@interface ALAppInfoPopoverController ()
@end


#pragma mark -
@implementation ALAppInfoPopoverController

@synthesize versionSlider;
@synthesize versionsArrayController;
@synthesize cachedVersions;


//-(void)awakeFromNib {
//    [[self versionsArrayController] setSortDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"releaseDate" ascending:YES]]];
//}

-(IBAction)setAppVersion:(id)sender {
    LogDebug(@"slider index %ld (%lu to %lu)", [[self versionSlider] integerValue], (NSUInteger)[[self versionSlider] minValue], (NSUInteger)[[self versionSlider] maxValue]);
    NSInteger versionIndex = [[self versionSlider] integerValue];
    ALVersion *selectedVersion = [[self cachedVersions] objectAtIndex:versionIndex];
    [[self representedObject] setCurrentVersion:selectedVersion];
}

-(void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];
    if (![representedObject isKindOfClass:[ALApp class]])
        return;
    ALApp *app = (ALApp *)representedObject;
    NSArray *versions = [[app versions] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"releaseDate" ascending:YES]]];
    [self setCachedVersions:versions];
    NSUInteger versionsCount = [versions count];
    NSUInteger currentVersionIndex = [versions indexOfObject:[app currentVersion]];
    [[self versionSlider] setIntegerValue:currentVersionIndex];
    [[self versionSlider] setMaxValue:versionsCount - 1];
    [[self versionSlider] setNumberOfTickMarks:versionsCount];
    [[self versionSlider] setEnabled:versionsCount > 1];
    LogDebug(@"setting up slider with %lu versions, %lu is current", versionsCount, currentVersionIndex);
}

@end
